﻿Imports System.Management
Namespace IO
  ''' <summary>
  ''' Drive helper mthods.
  ''' </summary>
  ''' <remarks></remarks>
  Public NotInheritable Class DriveHelper
    ''' <summary>
    ''' Finds the serial number of a drive.
    ''' </summary>
    ''' <param name="drive">Drive name.</param>
    ''' <returns>Serial number.</returns>
    ''' <remarks>This call could take some time. Recommend multi-threading.</remarks>
    Shared Function GetDriveSerialNumber(ByVal drive As String) As String
      Dim driveSerial As String = String.Empty

      'No matter what is sent in, get just the drive letter
      Dim driveFixed As String = System.IO.Path.GetPathRoot(drive)
      driveFixed = Replace(driveFixed, "\", String.Empty)

      'Perform Query
      Using querySearch As New ManagementObjectSearcher("SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '" & driveFixed & "'")
        Using queryCollection As ManagementObjectCollection = querySearch.Get()
          Dim moItem As ManagementObject
          For Each moItem In queryCollection
            driveSerial = CStr(moItem.Item("VolumeSerialNumber"))
            Exit For
          Next
        End Using
      End Using

      Return driveSerial

    End Function

    Private Sub New()
    End Sub

  End Class
End Namespace
